package com.beulemai.reader;

import java.io.IOException;
import java.net.MalformedURLException;

import touchimageview.TouchImageView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import comic.Comic;
import comic.Comic.Strip;

/**
 * Shows comic Strips and allows to navigate between them
 */
public class ComicViewActivity extends Activity {
	protected TouchImageView view = null;
	protected Comic comic = null;
	protected Strip strip = null;
	protected int last;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		// get the comic object out of the extras Bundle
		Bundle extras = getIntent().getExtras();
		comic = (Comic) extras.getSerializable("comic");

		int id = 0;
		try {
			last = comic.getLatest();
			id = extras.getInt("id", last);
		} catch (MalformedURLException e) {
			errormsg("Internet Connection Error");
		} catch (IOException e) {
			errormsg("Internet Connection Error");
		} catch (NumberFormatException e) {
			errormsg("Internet Connection Error");
		}
		// Initialize the View
		view = new TouchImageView(this);
		// download and display the strip
		displayStrip(id);
	}

	/**
	 * Downloads and shows the comic strip with the given id
	 */
	protected void displayStrip(int id) {
		try {
			Toast t = Toast.makeText(this, R.string.load_message,
					Toast.LENGTH_SHORT);
			t.show();
			strip = comic.getStrip(id);
			if (strip != null) {
				view.setBackgroundColor(Color.parseColor("#FFFFFF"));
				view.setImageDrawable(strip.image);
				setContentView(view);
				if (strip.title != "") {
					setTitle(strip.title);
				} else {
					setTitle(comic.toString() + " #" + strip.id);
				}
			}
			t.cancel();
		} catch (MalformedURLException e) {
			errormsg("Internet Connection Error");
		} catch (IOException e) {
			errormsg("Internet Connection Error");
		} catch (NumberFormatException e) {
			errormsg("Internet Connection Error");
		}
	}

	/**
	 * shows the previous comic strip
	 */
	protected void select_prev() {
		if (strip != null) {
			displayStrip(strip.id - 1);
			// update "lastread" when the user started navigating
			comic.lastread = strip.id;
		}
	}

	/**
	 * shows the next comic strip
	 */
	protected void select_next() {
		if (strip != null) {
			displayStrip(strip.id + 1);
			// update "lastread" when the user started navigating
			comic.lastread = strip.id;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Navigate through the strips by pressing the arrow keys
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			select_prev();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			select_next();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
			view.zoom(1.1f);
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
			view.zoom(1 / 1.1f);
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}

	@Override
	public void finish() {
		Intent answer = new Intent();
		// put the modified Comic objects in an Intent and send it back to the
		// caller
		answer.putExtra("comic", comic);
		setResult(RESULT_OK, answer);
		super.finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, 3, Menu.NONE, R.string.first_comic);
		menu.add(Menu.NONE, 0, Menu.NONE, R.string.continue_session);
		menu.add(Menu.NONE, 5, Menu.NONE, R.string.last_comic);

		menu.add(Menu.NONE, 1, Menu.NONE, R.string.previous_comic);
		menu.add(Menu.NONE, 4, Menu.NONE, R.string.alt_text);
		menu.add(Menu.NONE, 2, Menu.NONE, R.string.next_comic);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == 0) {
			displayStrip(comic.lastread);
		} else if (id == 1) {
			select_prev();
		} else if (id == 2) {
			select_next();
		} else if (id == 3) {
			displayStrip(comic.first_comic);
		} else if (id == 4) {
			messagebox(strip.text);
		} else if (id == 5) {
			displayStrip(last);
		}
		return true;
	}

	/**
	 * Shows a message box and terminates the Activity
	 * 
	 * @param msg
	 *            the error message
	 */
	protected void errormsg(String msg) {
		final Activity activity = this;
		AlertDialog ad = new AlertDialog.Builder(this).create();
		ad.setCancelable(false); // This blocks the 'BACK' button
		ad.setMessage(msg);
		ad.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				activity.finish();
			}
		});
		ad.show();
	}

	/**
	 * Shows a message box
	 * 
	 * @param msg
	 *            the message
	 */
	protected void messagebox(String msg) {
		AlertDialog ad = new AlertDialog.Builder(this).create();
		ad.setCancelable(false); // This blocks the 'BACK' button
		ad.setMessage(msg);
		ad.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		ad.show();
	}
}
